<?php
/**
 * Created by PhpStorm.
 * User: jjj
 * Date: 2017/11/20
 * Time: 16:49
 */

namespace app\common\model;


use think\Db;
use think\Model;

/**
 * Class VideoStorage
 * @package app\common\model
 *
 * @property integer id
 * @property string name
 * @property string netease_object
 * @property integer netease_vid
 * @property string netease_orig_addr
 * @property string netease_encrypt
 * @property integer netease_status
 * @property string created
 */
class VideoStorage extends Model
{
    protected $table = 'video_storage';
    protected $pk = 'id';

    const NETEASE_STATUS_BEFORE_UPLOAD = 1;
    const NETEASE_STATUS_UPLOADING = 2;
    const NETEASE_STATUS_UPLOAD_FINISH = 3;
    const NETEASE_STATUS_TRANSCODE_FINISH = 4;
    const NETEASE_STATUS_ENCRYPT_FINISH = 5;

    /**
     * @param $vid
     * @return null|static
     */
    public static function getByVID($vid) {
        return self::get([
            'netease_vid' => $vid,
        ]);
    }

    /**
     * 创建播放视频
     *
     * @param $encryptId
     * @param $style
     */
    public function createEncrypt($encryptId, $style) {
        $sql = <<<SQL
INSERT INTO netease_encrypt (encrypt_id, video_storage_id, style) VALUES 
(:encrypt_id, :video_storage_id, :style)
SQL;
        Db::execute($sql, [
            'encrypt_id' => $encryptId,
            'video_storage_id' => $this->id,
            'style' => $style,
        ]);
    }

    /**
     * 保存加密视频播放地址
     *
     * @param $encryptId
     * @param $url
     */
    public static function storeEncrypt($encryptId, $url) {
        $sql = <<<SQL
UPDATE netease_encrypt 
SET play_url = :url, finish = TRUE
WHERE encrypt_id=:id
SQL;
        Db::execute($sql, [
            'id' => $encryptId,
            'url' => $url,
        ]);
    }

    /**
     * 获取加密视频播放地址
     *
     * @param $vid
     * @param $style
     * @return mixed
     */
    public static function getEncryptUrl($vid, $style) {
        $sql = <<<SQL
SELECT ne.*
FROM netease_encrypt ne 
WHERE ne.video_storage_id=:vid AND ne.style=:style AND ne.finish=TRUE 
ORDER BY ne.encrypt_id DESC 
LIMIT 1
SQL;
        $re = Db::query($sql, ['vid'=>$vid, 'style'=>$style,]);
        return $re[0] ?? null;
    }

    /**
     * 获取所有加密视频
     *
     * @param $vid
     * @return mixed
     */
    public static function getEncrypt($vid) {
        $sql = <<<SQL
SELECT * FROM netease_encrypt WHERE video_storage_id=:vid
SQL;
        $list = Db::query($sql, ['vid' => $vid]);
        return $list;
    }

    /**
     * 删除加密视频
     *
     * @param $vid
     */
    public static function deleteEncrypt($vid) {
        $sql = <<<SQL
DELETE FROM netease_encrypt WHERE video_storage_id=:vid
RETURNING *
SQL;
        Db::execute($sql, ['vid' => $vid]);
    }

}